<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item prop="link" label="link">
        <el-input v-model="ruleForm.link" type="link" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="alt" label="alt">
        <el-input v-model="ruleForm.alt" type="alt" autocomplete="off" />
      </el-form-item>
      <el-form-item label="图片">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          style="border: 1px dashed black"
          :http-request="httprequestFn"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <!-- base64图片路径 -->
      <el-form-item prop="img" label="base64">
        <el-input v-model="ruleForm.img" type="alt" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 导入图标组件
import { Plus } from '@element-plus/icons-vue'
import { addswiperFn } from '@/utils/swiper'
export default {
  name: '',
  data() {
    return {
      ruleForm: {
        // 上传图片的接口数据
        link: '',
        img: '',
        alt: ''
      },
      imageUrl: '', // 上传的图片路径
      rules: {
        //验证规则
        link: [{ required: true, message: '请输入link', trigger: 'blur' }],
        img: [{ required: true, message: '请输入img的base64路径', trigger: 'blur' }],
        alt: [{ required: true, message: '请输入alt', trigger: 'blur' }]
      },
      ruleFormRef: null // form表单组件实例对象
    }
  },
  mounted() {
    this.ruleFormRef = this.$refs.ruleFormRef
  },
  methods: {
    // 提交表单
    submitForm(formEl) {
      //   console.log(formEl)
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          // 调用上传图片接口
          addswiperFn(this.ruleForm).then((res) => {
            console.log('上传接口', res)
            if (res.data.code == 200) {
              // 跳转到轮播图列表页
              this.$router.push({ name: 'swiperlist' })
            }
          })
        } else {
          console.log('error submit!')
          return false
        }
      })
    },
    // 重置表单
    resetForm(formEl) {
      if (!formEl) return
      formEl.resetFields()
    },
    // 点击+ 上传触发的执行函数
    httprequestFn(data) {
      // console.log('data', data.file) // data.file 就是上传的文件信息
      let imgtypeArr = ['image/jpeg', 'image/jpg', 'image/png']
      if (imgtypeArr.indexOf(data.file.type) == -1) {
        ElMessage.error('上传的图片格式错误')
        return false
      } else if (data.file.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小超过了2M!')
        return false
      }

      // 赋值图片路径, 将data.file 这个上传的文件转成图片路径
      //console.log(URL.createObjectURL(data.file))
      this.imageUrl = URL.createObjectURL(data.file)

      // 将上传的图片转成base64 格式,由于转base64的过程是异步过程, 所以,可以使用
      // promise封装异步转成base64的过程,相当于之前学过的promise 封装ajax
      this.getimgbase64Fn(data.file).then((res) => {
        //console.log('base64', res)
        //给表单项img赋值
        this.ruleForm.img = res
      })
    },
    // 封装的将图片转成base64方法
    getimgbase64Fn(file) {
      // file 就是你要转成base64路径的图片文件
      return new Promise((resove, reject) => {
        // 写异步代码
        // 01: 创建一个读取器
        let reader = new FileReader()
        let fileResult = '' // 表示读取的文件的结果
        // 02: 设置要读取的文件 参数就是要读取的文件
        reader.readAsDataURL(file)
        // console.log('reader', reader)
        // 03: 读取的过程中, 转成base64的过程中
        reader.onload = () => {
          fileResult = reader.result
        }

        // 04: 读取错误的时候
        reader.onerror = (error) => {
          reject(error)
        }
        // 05:读取成base64格式完成
        reader.onloadend = () => {
          resove(fileResult)
        }
      })
    }
  },
  components: {
    Plus
  }
}
</script>
<style lang='scss' scoped>
.el-form {
  width: 300px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
